<?php

namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use Rennokki\QueryCache\Traits\QueryCacheable;

class Notebook extends Base
{
    use SoftDeletes, QueryCacheable;
    public $cacheFor = 300;
    public $cacheTags = ['notebooks'];
    protected static $flushCacheOnUpdate = true;

    protected $casts = [
        'file_path' => 'array'
    ];
    protected $fillable = ['user_id', 'cookbook_id', 'message', 'file_path'];

    public function getCacheTagsToInvalidateOnUpdate(): array
    {
        return [
            'max_updated_at',
        ];
    }

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $updated_at = Notebook::cacheTags(['max_updated_at'])->withTrashed()->max('updated_at');
        $this->cacheTags[0] = 'notebooks_' . strtotime($updated_at);
    }

    public function cookbook() {
        return $this->belongsTo(Cookbook::class, 'cookbook_id');
    }

    public function is_star() {
        return $this->hasOne(Star::class, 'entity_id')->where('type', Star::TYPE_NOTEBOOK);
    }

    public function user() {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function is_focus() {
        return $this->hasOne(Focus::class, 'target_user_id', 'user_id');
    }

    public function setFilePathAttribute($file_path) {
        $this->attributes['file_path'] = $file_path;
    }

}
